package com.linzm.leetcode.primary.exercises2_20230116;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author zimingl
 * @Date 2023/1/16 21:14
 * @Description: 一周中的第几天
 */
public class Demo2_1185 {
    /**
     * 输入：day = 31, month = 8, year = 2019
     * 输出："Saturday"
     */
    public static void main(String[] args) {
        Demo2_1185 demo2_1185 = new Demo2_1185();
        int day = 31, month = 8, year = 2019;
        String s = demo2_1185.dayOfTheWeek2(day, month, year);
        System.out.println(s);
    }

    private String dayOfTheWeek(int day, int month, int year) {
        String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        int[] mon1 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int[] mon2 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int sum = 0;
        if (year % 4 != 0) {
            for (int i = 0; i < month; i++) {
                sum += mon1[i];
            }
            sum += day;
        } else {
            for (int i = 0; i < month; i++) {
                sum += mon2[i];
            }
            sum += day;
        }
        return week[(sum % 7) + 1];
    }

    private String dayOfTheWeek2(int day, int month, int year) {
        String datetime = year + "";
        if (month < 10) {
            datetime += "-" + "0" + month;
        } else {
            datetime += "-" + month;
        }
        if (day < 10) {
            datetime += "-" + "0" + day;
        } else {
            datetime += "-" + day;
        }
        String[] weekDays = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date date = null;
        try {
            date = simpleDateFormat.parse(datetime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week < 0) {
            week = 0;
        }
        return weekDays[week];
    }
}

